package com.lemon.smartsafety.ui.activity.user;

import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.entity.event.user.UrlSettingEvent;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;

import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_FILES_BASE_URL;
import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_FILES_PORT;
import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_FILES_VIRTUAL_DIRECTORY;
import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_HTTP_BASE_URL;
import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_HTTP_PORT;
import static com.lemon.smartsafety.app.Constants.TEST_KEY_CL_HTTP_VIRTUAL_DIRECTORY;

/**
 * Created by Cooliean on 16/1/19.
 * 服务器地址设置
 */
public class SettingUrlActivity extends SwipeBackActivity {

    private MaterialDialog.Builder mMaterialDialog;

    private SharedPreferencesServer mSharedPreferencesServer;

    @Bind(R.id.editHostUrl)
    MaterialEditText editHostUrl;

    @Bind(R.id.editHostPort)
    MaterialEditText editHostPort;

    @Bind(R.id.editHostVD)
    MaterialEditText editHostVD;

    @Bind(R.id.editFileUrl)
    MaterialEditText editFileUrl;

    @Bind(R.id.editFilePort)
    MaterialEditText editFilePort;

    @Bind(R.id.editFileVD)
    MaterialEditText editFileVD;


    @Bind(R.id.btnSubmit)
    Button btnSubmit;


    private String sHostUrl, sHostPort, sHostVD;
    private String sFilesUrl, sFilesPort, sFilesVD;

    /**
     * 提示信息对话框
     */
    private HUDUtil mHUDUtil;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_url_setting;
    }

    @Override
    protected void initTitle() {
        this.setBarTitle(getString(R.string.setting_url_title));
    }

    @Override
    protected void initViews() {
        super.initViews();
        mHUDUtil=new HUDUtil();
        mHUDUtil = mHUDUtil.init(SettingUrlActivity.this);
        //mHUDUtil = HUDUtil.init(SettingUrlActivity.this);
        mSharedPreferencesServer = new SharedPreferencesServer(this);

        initValueView();


    }

    private void initValueView() {
        editHostUrl.setText(mSharedPreferencesServer.getHttpBaseHost());
        editHostPort.setText(mSharedPreferencesServer.getHttpBaseHostPort());
        editHostVD.setText(mSharedPreferencesServer.getHttpBaseHostVD());

        editFileUrl.setText(mSharedPreferencesServer.getFileBaseHost());
        editFilePort.setText(mSharedPreferencesServer.getFileBasePort());
        editFileVD.setText(mSharedPreferencesServer.getFileBaseVD());
    }

    @Override
    protected void initListener() {
        btnSubmit.setOnClickListener(viewClickListener);
    }

    private View.OnClickListener viewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btnSubmit) {
                doSubmitAction();
            }
        }
    };

    private void doSubmitAction() {
        if (!validateForm()) return;
        doSaveTip();
    }

    private void doSaveTip() {
        mMaterialDialog = new MaterialDialog.Builder(this).content(R.string.setting_url_sure_save).positiveText(R.string.sure_str).negativeText(R.string.cancel_str).onAny(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doSave();
                    tipClose();
                }
            }
        });
        mMaterialDialog.show();
    }

    private void tipClose() {
        //提示后销毁界面
        mHUDUtil.showDoneTip(getString(R.string.setting_url_save_success), new HUDUtil.CallBack() {
            @Override
            public void onCall() {
                UrlSettingEvent event = new UrlSettingEvent();
                event.setTag(SettingUrlActivity.class.getName());
                AppService.getBus().post(event);
                AppManager.getAppManager().finishActivity(SettingUrlActivity.class);
            }
        });
    }

    private boolean validateForm() {
        sHostUrl = editHostUrl.getText().toString().trim();
        if (sHostUrl.length() == 0) {
            editHostUrl.setError(getString(R.string.setting_url_http_host_please));
            return false;
        }
        sHostPort = editHostPort.getText().toString().trim();
        if (sHostPort.length() == 0) {
            editHostPort.setError(getString(R.string.setting_url_http_port_please));
            return false;
        }
        sHostVD = editHostVD.getText().toString().trim();
        if (sHostVD.length() == 0) {
            editHostVD.setError(getString(R.string.setting_url_http_vd_please));
            return false;
        }


        sFilesUrl = editFileUrl.getText().toString().trim();
        if (sFilesUrl.length() == 0) {
            editFileUrl.setError(getString(R.string.setting_url_files_host_please));
            return false;
        }
        sFilesPort = editFilePort.getText().toString().trim();
        if (sFilesPort.length() == 0) {
            editFilePort.setError(getString(R.string.setting_url_files_port_please));
            return false;
        }
        sFilesVD = editFileVD.getText().toString().trim();
        if (sFilesVD.length() == 0) {
            editFileVD.setError(getString(R.string.setting_url_files_vd_please));
            return false;
        }

        return true;
    }


    private void doSave() {
        mSharedPreferencesServer.setHttpBaseHost(sHostUrl).setHttpBaseHostPort(sHostPort).setHttpBaseHostVD(sHostVD);
        mSharedPreferencesServer.setFileBaseHost(sFilesUrl).setFileBasePort(sFilesPort).setFileBaseVD(sFilesVD);
        initValueView();
    }


    @Override
    protected void callFinish() {
        mHUDUtil = null;
        mMaterialDialog = null;
        mSharedPreferencesServer = null;
        AppManager.getAppManager().finishActivity(SettingUrlActivity.class);
    }


    @Subscribe
    public void onEventMainThread(AppEvent event) {
        return;
    }



    private void resetUrlSetting(boolean isDev) {
        if (isDev) {
            String sIpAddress = AppUtils.getLocalIp(this);
            if (sIpAddress.startsWith("202.115.18")) {
                TEST_KEY_CL_HTTP_BASE_URL = "202.115.18.11";
            } else if (sIpAddress.startsWith("10.0.1")) {
                TEST_KEY_CL_HTTP_BASE_URL = "10.0.1.99";
            } else if (sIpAddress.startsWith("192.168.3")) {
                TEST_KEY_CL_HTTP_BASE_URL = "192.168.3.15";
            }
            TEST_KEY_CL_FILES_BASE_URL = TEST_KEY_CL_HTTP_BASE_URL;
            mSharedPreferencesServer.setHttpBaseHost(TEST_KEY_CL_HTTP_BASE_URL).setHttpBaseHostPort(TEST_KEY_CL_HTTP_PORT).setHttpBaseHostVD(TEST_KEY_CL_HTTP_VIRTUAL_DIRECTORY);
            mSharedPreferencesServer.setFileBaseHost(TEST_KEY_CL_FILES_BASE_URL).setFileBasePort(TEST_KEY_CL_FILES_PORT).setFileBaseVD(TEST_KEY_CL_FILES_VIRTUAL_DIRECTORY);
        } else {
            mSharedPreferencesServer.setHttpBaseHost(Constants.DEFAULT_KEY_CL_HTTP_BASE_URL).setHttpBaseHostPort(Constants.DEFAULT_KEY_CL_HTTP_PORT).setHttpBaseHostVD(Constants.DEFAULT_KEY_CL_HTTP_VIRTUAL_DIRECTORY);
            mSharedPreferencesServer.setFileBaseHost(Constants.DEFAULT_KEY_CL_FILES_BASE_URL).setFileBasePort(Constants.DEFAULT_KEY_CL_FILES_PORT).setFileBaseVD(Constants.DEFAULT_KEY_CL_FILES_VIRTUAL_DIRECTORY);
        }

        initValueView();
        tipClose();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setIconEnable(menu, true);
        getMenuInflater().inflate(R.menu.menu_setting_url, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_url_reset: {
                mMaterialDialog = new MaterialDialog.Builder(this).content(R.string.setting_url_menu_reset_sure).positiveText(R.string.sure_str).negativeText(R.string.cancel_str).onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            resetUrlSetting(false);
                        }
                    }
                });
                mMaterialDialog.show();
                break;
            }
            case R.id.action_url_dev: {
                mMaterialDialog = new MaterialDialog.Builder(this).content(R.string.setting_url_menu_reset_dev_sure).positiveText(R.string.sure_str).negativeText(R.string.cancel_str).onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            resetUrlSetting(true);
                        }
                    }
                });
                mMaterialDialog.show();
                break;
            }

        }

        return super.onOptionsItemSelected(item);
    }

}
